package com.ym.wcp.framework.advice;

import cn.hutool.log.Log;
import cn.hutool.log.dialect.log4j.Log4jLogFactory;
import com.ym.wcp.framework.exception.BizException;
import com.ym.wcp.framework.response.R;
import com.ym.wcp.framework.utils.ExceptionInfoUtil;
import org.springframework.util.StringUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@ControllerAdvice
@ResponseBody
public class DefaultGlobalExceptionHandler {

    private static final Log LOG = new Log4jLogFactory().createLog(DefaultGlobalExceptionHandler.class);

    @ExceptionHandler(BizException.class)
    public R<?> bizExceptionHandler(BizException ex, HttpServletRequest request) {
        String errMsg = !StringUtils.isEmpty(ex.getMessage()) ? ex.getMessage() : ex.getLocalizedMessage();
        LOG.error("BIZ EXCEPTION:", ex);
        LOG.error("ERROR_URL = {}" + request.getRequestURI());
        LOG.error("ERROR_MSG = {}" + errMsg);
        String errorMessage = ExceptionInfoUtil.printStackTrace(ex);
        return R.result(ex.getCode(), null, errorMessage).setPath(request.getRequestURI());
    }

    @ExceptionHandler(Exception.class)
    public R<?> globalExceptionHandler(Exception ex, HttpServletRequest request) {
        String errMsg = !StringUtils.isEmpty(ex.getMessage()) ? ex.getMessage() : ex.getLocalizedMessage();
        LOG.error("EXCEPTION:", ex);
        LOG.error("ERROR_URL = {}" + request.getRequestURI());
        LOG.error("ERROR_MSG = {}" + errMsg);
        String errorMessage = ExceptionInfoUtil.printStackTrace(ex);
        return R.result(-1, null, errorMessage).setPath(request.getRequestURI());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<?> methodArgumentNotValidHandler(MethodArgumentNotValidException ex, HttpServletRequest request) {
        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        String message = null;
        if (allErrors != null && allErrors.size() > 0) {
            message = allErrors.get(0).getDefaultMessage();
        }
        return R.result(-1, null, message).setPath(request.getRequestURI());
    }
}
